import ZcoIM from '../index';

export function sendMessageToRecord (type, msg, user, status) {
    if (!user) {
        user = ZcoIM.agent;
    }
    type = type ? type : 'text';
    let message = {
        type: '',
        clientId: '',
        date: new Date(),
        from: '',
        label: '',
        fromUser: {},
        data: '',
        id: '',
        status: '',
        isBusinessMessage: false
    };
    message.type = type;
    message.clientId = user.clientId || '';
    message.date = getCurrentDate();

    message.from = user.id;
    message.label = user.role;
    message.fromUser = {
        id: user.id,
        name: user.userName || user.name,
        avatar: user.picture || user.avatar,
        isRobot: user.isRobot || false
    };
    message.data = formatMessage(type, msg);
    message.id = generateId();
    message.status = status;
    return message;
}

/**
 * 格式化消息
 * @param { String } type 消息类型
 * @param { Object } msg 消息体
 * @returns 格式化后消息体
 */
export function formatMessage (type, msg) {
    console.log('zco-im-formatMessage:', msg, new Date());
    let result = '';
    switch (type) {
        case 'text':
            result = msg.text ? msg.text : msg.data ? (msg.data === 'silence-msg' ? '- -' : msg.data) : msg;
            break;
        case 'link':
            if (msg.data) {
                result = { type: msg.data.type, url: msg.data.url, name: msg.data.name, size: msg.data.size, suffix: msg.data.suffix, file: msg.data.file };
            } else {
                result = { type: msg.type, url: msg.url, name: msg.name, size: msg.size, suffix: msg.suffix ? msg.suffix : '', file: msg.file };
            }

            break;
        default:
            result = '';
            break;
    }
    return result;
}

export function getCurrentDate () {
    return new Date();
}

//生成唯一值id
const generateId = () => {
    const s = [];
    const hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    // bits 12-15 of the time_hi_and_version field to 0010
    s[14] = '4';
    // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = '-';
    const uuid = s.join('');
    return uuid;
};

export function getMsgType (type) {
    return (
        type === 'peer-cmd' ||
        type === 'peer-cancel' ||
        type === 'peer-response' ||
        type === 'screen-share' ||
        type === 'stop-screen-share' ||
        type === 'screen-record' ||
        type === 'stop-screen-record' ||
        type === 'ocr' ||
        type === 'start-tts-speaking' ||
        type === 'cancel-tts-speaking' ||
        type === 'invite' ||
        type === 'ai-checkout' ||
        type === 'request-upgrade' ||
        type === 'cancel-upgrade' ||
        type === 'accept-upgrade' ||
        type === 'reject-upgrade' ||
        type === 'start-recording' ||
        type === 'stop-recording' ||
        type === 'system-start-recording' ||
        type === 'system-stop-recording'
    );
}

export function formatSessionMessageRecords (records) {
    let map = new Map();
    let result = [];
    records.forEach(msg => {
        // 系统开始双录消息不显示
        if (msg.fromClientId === 'system' && ['start-recording', 'stop-recording', 'system-start-recording', 'system-stop-recording'].includes(msg.msgType)) {
            return;
        }
        if (msg.msgType === 'peer-status' && msg.data.status === 'joined') {
            let user = {
                clientId: msg.data.id,
                role: msg.data.role,
                id: msg.data.user.id,
                userName: msg.data.user.name,
                isRobot: msg && msg.data && msg.data.user && msg.data.user.profile ? msg.data.user.profile.isRobot : false
            };
            map.set(msg.data.id, user);
        }
        if (msg.fromClientId === 'system') {
            if (msg && msg.data && msg.data.status === 'joined' && msg.data.clinetWhoInvitateCustomer && ZcoIM.showBusinessMessage) {
                result.push({
                    type: 'invite-customer',
                    clientId: msg.data.clinetWhoInvitateCustomer.id,
                    date: msg.createdAt,
                    from: msg.data.clinetWhoInvitateCustomer.user.id,
                    label: msg.data.clinetWhoInvitateCustomer.role,
                    fromUser: {
                        id: msg.data.clinetWhoInvitateCustomer.user.id,
                        name: msg.data.clinetWhoInvitateCustomer.user.name,
                        avatar: '',
                        isRobot: map.get(msg.data.clinetWhoInvitateCustomer.id) ? map.get(msg.data.clinetWhoInvitateCustomer.id).isRobot : false
                    },
                    data: msg.data,
                    id: generateId(),
                    toUserInfo: {},
                    fromUserInfo: {},
                    invitation: '',
                    isBusinessMessage: ZcoIM.showBusinessMessage
                })
            }
            if (msg && msg.data && (msg.data.status === 'joined' || msg.data.status === 'quit')) {
                let data = systemSessionRecord(msg.data);
                result.push(data);
            }
        }
        if (msg.msgType === 'text' || msg.msgType === 'link') {
            let data = filterClientMessage(msg, map);
            result.push(data);
        }
        if (getMsgType(msg.msgType) && ZcoIM.showBusinessMessage) {
            if (msg.msgType === 'peer-response' && msg.data.cmd === 'customer-view-mark') return; // 访客接受/拒绝实时标注
            if (msg.msgType === 'peer-response' && msg.data.status === 'in-progress') return;
            if (msg.data && msg.data.cmd === 'co-browsing' && msg.msgType === 'peer-cmd' && msg.data.data.type === 'request-customer-size') return;
            if (msg.data && msg.data.cmd === 'co-browsing' && msg.msgType === 'peer-response' && msg.data.data.action === 'endScreenSync') return;
            if (msg.data && (msg.data.cmd === 'make-choice' || msg.data.cmd === 'third-nlp')) return;
            if (msg.data && msg.msgType === 'peer-cmd' && msg.data.cmd === 'view' && msg.data.data && msg.data.data.type === 'messageSummary' && msg.data.data.nodeType === 'messageSummary') return
            if (msg.data && msg.msgType === 'peer-cmd' && msg.data.cmd === 'browsing-mark') return;
            if (msg.data && msg.msgType === 'ai-checkout' && msg.data.status === 'detect-living-face') return;
            if (ZcoIM.ignoreMessageType.includes(msg.msgType)) return;
            const message = businessMessageRecord(msg, map);
            result.push(message);
        }
    });
    console.log(result, '洗过之后的数据');
    return result;
}

export function businessMessageRecord (data, map) {
    let message = {
        type: '',
        clientId: '',
        date: data.createdAt,
        from: '',
        label: '',
        fromUser: {},
        data: '',
        id: '',
        toUserInfo: {},
        fromUserInfo: {},
        invitation: '',
        isBusinessMessage: ZcoIM.showBusinessMessage
    };
    message.type = data.msgType;
    message.clientId = data.fromClientId || '';
    message.date = data.createdAt || getCurrentDate();
    message.from = data.fromUserId || '';
    message.label = data.fromUserRole || '';
    message.fromUser = {
        id: data.fromUserId ? data.fromUserId.id : '',
        name: data.fromUserName || '',
        avatar: data.fromUserAvatar || '',
        isRobot: map.get(data.fromClientId) ? map.get(data.fromClientId).isRobot : false
    };
    message.id = generateId();
    message.toUserInfo = data.toUserInfo;
    message.fromUserInfo = data.fromUserInfo;
    message.data = data.data;
    message.invitation = data.invitation;
    return message;
}

export function setReceiveBusinessMessage (data, resourceOriginUrlDomain = '', resourceReplaceUrlDomain = '', urlMapping = {}) {
    let message = {
        type: '',
        clientId: '',
        date: data.createdAt,
        from: '',
        label: '',
        fromUser: {},
        data: '',
        id: '',
        toUserInfo: {},
        fromUserInfo: {},
        invitation: '',
        isBusinessMessage: ZcoIM.showBusinessMessage
    };
    message.type = data.msgType;
    message.clientId = data.fromClientId || '';
    message.date = data.createdAt || getCurrentDate();
    message.from = data.fromUserId || '';
    message.label = data.fromUserRole || '';
    message.fromUser = {
        id: data.fromUserId ? data.fromUserId.id : '',
        name: data.fromUserName || '',
        avatar: data.fromUserAvatar || '',
        isRobot: data.fromUserInfo && data.fromUserInfo.isRobot ? data.fromUserInfo.isRobot : false
    };
    message.id = generateId();
    message.toUserInfo = data.toUserInfo;
    message.fromUserInfo = data.fromUserInfo;
    // 替换link的url | imageUrl | urls | data
    if (resourceOriginUrlDomain && resourceReplaceUrlDomain && data.data && data.data.data) {
        const { url, imageUrl, urls } = data.data.data;
        if (url && url.indexOf(resourceOriginUrlDomain) !== -1) {
            data.data.data.url = url.replace(resourceOriginUrlDomain, resourceReplaceUrlDomain);
        } else if (imageUrl && imageUrl.indexOf(resourceOriginUrlDomain) !== -1) {
            data.data.data.imageUrl = imageUrl.replace(resourceOriginUrlDomain, resourceReplaceUrlDomain);
        } else if (urls && urls.length > 0) {
            urls.forEach(item => {
                if (item.url && item.url.indexOf(resourceOriginUrlDomain) !== -1) {
                    item.url = item.url.replace(resourceOriginUrlDomain, resourceReplaceUrlDomain);
                }
            });
        } else if (data.data.data.data && typeof data.data.data.data === 'string' && data.data.data.data.indexOf(resourceOriginUrlDomain) !== -1) {
            data.data.data.data = data.data.data.data.replace(resourceOriginUrlDomain, resourceReplaceUrlDomain);
        }
    }
    // 替换urlMapping中的url
    if (Object.keys(urlMapping).length > 0 && data.data && data.data.data) {
        const { url, imageUrl, urls } = data.data.data;
        Object.keys(urlMapping).forEach(key => {
            if (url && url.indexOf(key) !== -1) {
                data.data.data.url = url.replace(key, urlMapping[key]);
            } else if (imageUrl && imageUrl.indexOf(key) !== -1) {
                data.data.data.imageUrl = imageUrl.replace(key, urlMapping[key]);
            } else if (urls && urls.length > 0) {
                urls.forEach(item => {
                    if (item.url && item.url.indexOf(key) !== -1) {
                        item.url = item.url.replace(key, urlMapping[key]);
                    }
                });
            } else if (data.data.data.data && typeof data.data.data.data === 'string' && data.data.data.data.indexOf(key) !== -1) {
                data.data.data.data = data.data.data.data.replace(key, urlMapping[key]);
            }
        });
    }
    message.data = data.data;
    message.invitation = data.invitation;

    console.log('zco-im-setReceiveBusinessMessage:', data, resourceOriginUrlDomain, resourceReplaceUrlDomain, urlMapping);
    return message;
}

export function filterClientMessage (data, map) {
    let message = {
        type: '',
        clientId: '',
        date: data.createdAt,
        from: '',
        label: '',
        fromUser: {},
        data: '',
        id: '',
        isBusinessMessage: false
    };
    message.type = formatMessageType(data);
    message.clientId = data.fromClientId || '';
    message.date = data.createdAt || getCurrentDate();
    message.from = data.fromUserId || '';
    message.label = data.fromUserRole || '';
    message.fromUser = {
        id: data.fromUserId ? data.fromUserId.id : '',
        name: data.fromUserName || '',
        avatar: data.fromUserAvatar || '',
        isRobot: map.get(data.fromClientId) ? map.get(data.fromClientId).isRobot : false
    };
    message.id = generateId();
    message.data = formatMessage(message.type, data);
    return message;
}

export function systemSessionRecord (data) {
    let message = {
        type: '',
        id: '',
        date: '',
        from: '',
        label: '',
        fromUser: {},
        data: '',
        isBusinessMessage: false
    };
    message.type = 'text';
    message.id = '';
    message.date = data.at || data.createdAt || getCurrentDate();
    message.from = 'stytem';
    message.label = 'system';
    message.fromUser = {
        id: '',
        name: '系统消息',
        avatar: ''
    };
    message.data = `${getUsertName(data)} ${getUsertStatus(data.status)}`;
    console.log('zcom-im -systemSessionRecord:', data, message);
    return message;
}

export function formatMessageType (data) {
    let type = '';
    switch (data.msgType) {
        case 'peer-response':
            type = data.data.cmd;
            break;
        case 'peer-cmd':
            type = data.data.cmd;
            break;
        default:
            type = data.msgType;
            break;
    }
    return type;
}

export function getUsertName (data) {
    let result = '';
    switch (data.role) {
        case 'agent':
            result = `坐席<${data.user.name}>`;
            break;
        case 'customer':
            result = `访客<${data.user.name}>`;
            break;
        default:
            result = '';
            break;
    }
    return result;
}

/**
 *
 * @param { String } status 状态
 * @returns
 */
export function getUsertStatus (status) {
    let result = '';
    switch (status) {
        case 'joined':
            result = '加入会话';
            break;
        case 'quit':
            result = '离开会话';
            break;
        default:
            result = '';
            break;
    }
    return result;
}

export function formatMessageTime (sourceTime) {
    var date = new Date(sourceTime);
    // var y = date.getFullYear();
    // var m = date.getMonth() + 1;
    // m = m < 10 ? ('0' + m) : m;
    // var d = date.getDate();
    // d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    minute = minute < 10 ? '0' + minute : minute;
    let time = h + ':' + minute;
    return time;
}

/**
 * 留痕会话中，坐席加入 / 离开会话的消息
 * @param { Object } user 用户数据
 * @returns { Object } 消息体
 */
export function userInSessionRecord (user) {
    let message = {
        type: '',
        id: '',
        date: '',
        from: '',
        label: '',
        fromUser: {},
        data: '',
        isBusinessMessage: false
    };
    message.type = 'text';
    message.id = '';
    message.date = user.at;
    message.from = 'stytem';
    message.label = 'system';
    message.fromUser = {
        id: '',
        name: '系统消息',
        avatar: ''
    };
    let role = user.role === 'customer' ? '访客' : '坐席';
    message.data = `${role}<${user.user.name}>${getUsertStatus(user.status)}`;
    console.log('zcom-im -message:', message, new Date());
    return message;
}
